/**
 * @(#)MiguUserCheckThread.java 2017年12月26日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.task;

import java.security.Security;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jsbd.boss.domian.channel.ClientEffectVo;
import org.jsbd.boss.domian.channel.ClientRecordVo;
import org.jsbd.boss.domian.channel.MiguUser;
import org.jsbd.boss.enums.LoginTypeEnum;
import org.jsbd.boss.enums.MiguTableEnum;
import org.jsbd.boss.httpclient.HttpClientUtil;
import org.jsbd.boss.httpclient.vo.Request;
import org.jsbd.boss.httpclient.vo.Response;
import org.jsbd.boss.service.ClientManager;
import org.jsbd.boss.util.PropertiesUtil;
import org.jsbd.boss.util.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.webmeng.market.task.migu.apk.MiguAuthorization;
import org.webmeng.market.task.migu.apk.util.MiguLoginParam;

import com.alibaba.fastjson.JSONObject;

import edu.hziee.common.queue.DelayExecuteBuffer;

/**
 * TODO 请加入本类的说明
 * 
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
public class MiguUserCheckThread implements Runnable {
	public static final Logger LOGGER = LoggerFactory.getLogger(MiguUserCheckThread.class);

	private DelayExecuteBuffer<MiguUser> allMiguUserUpdateBuffer = SpringContextUtils.getBean("allMiguUserUpdateBuffer");

	private DelayExecuteBuffer<ClientRecordVo> miguRecordDelBuffer = SpringContextUtils.getBean("miguRecordDelBuffer");

	private DelayExecuteBuffer<ClientEffectVo> miguEffectDelBuffer = SpringContextUtils.getBean("miguEffectDelBuffer");

	private ClientManager clientManager = SpringContextUtils.getBean("clientManager");

	private String MIGU_CHECK_URL = PropertiesUtil.getValue("migu_check_url", "http://118.178.158.159:8100/migu/register/login");

	private MiguUser miguUser;
	private Set<Integer> baseOrApkIdSet;

	/**
	 * create an instance of MiguUserChcekServiceImpl.MiguUserCheckThread
	 */
	public MiguUserCheckThread(MiguUser miguUser, Set<Integer> baseOrApkIdSet) {
		this.miguUser = miguUser;
		this.baseOrApkIdSet = baseOrApkIdSet;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		int code = checkMiguUser2(miguUser);
		// 校验没通过
		checkImsiAndImei(miguUser);
		miguUser.setIsUseful(code);
		int dataSource = miguUser.getDataSource();
		if (dataSource == LoginTypeEnum.MIGU.getType()) {
			miguUser.setTableName(MiguTableEnum.HISTORY_MIGU.getCode());
		} else if (dataSource == LoginTypeEnum.THIRD_MIGU.getType()) {
			miguUser.setTableName(MiguTableEnum.THIRD_MIGU.getCode());
		} else if (dataSource == LoginTypeEnum.SELF_MOBILE_MIGU.getType()) {
			miguUser.setTableName(MiguTableEnum.SELF_MOBILE_MIGU.getCode());
		}else if (dataSource == LoginTypeEnum.SELF_UNICOM_MIGU.getType()) {
			miguUser.setTableName(MiguTableEnum.SELF_UNICOM_MIGU.getCode());
		}else if (dataSource == LoginTypeEnum.SELF_TELECOM_MIGU.getType()) {
			miguUser.setTableName(MiguTableEnum.SELF_TELECOM_MIGU.getCode());
		}
		allMiguUserUpdateBuffer.add(miguUser);
		if (code != 1) {
			if (baseOrApkIdSet != null) {
				for (Integer apkId : baseOrApkIdSet) {
					ClientRecordVo clientVo = new ClientRecordVo();
					clientVo.setImsi(miguUser.getImsi());
					clientVo.setPostfix(apkId);
					// 删除record表记录
					miguRecordDelBuffer.add(clientVo);
					ClientEffectVo effectVo = new ClientEffectVo();
					effectVo.setImsi(miguUser.getImsi());
					effectVo.setPostfix(apkId);
					miguEffectDelBuffer.add(effectVo);
				}
			}
		}
	}

	/**
	 * checkImsiAndImei:TODO 请描述该方法是做什么用途的
	 * 
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @param miguUser2
	 */
	private void checkImsiAndImei(MiguUser miguUser) {
		String imei = clientManager.checkAndGetImsiAndImei(miguUser.getImsi(), miguUser.getImei());
		if (imei != null) {
			miguUser.setImei(imei);
		}
	}

	private int checkMiguUser2(MiguUser miguUser) {
		int code = -1;
		Map<String, String> result = null;
		MiguLoginParam loginParam = new MiguLoginParam();
		try {
			Security.addProvider(new BouncyCastleProvider());
			loginParam.setAndroidId(miguUser.getAndroidId());
			loginParam.setBuildId(miguUser.getBuildId());
			loginParam.setBuildVersion(miguUser.getBuildVersion());
			loginParam.setHsman(miguUser.getHsman());
			loginParam.setHstype(miguUser.getHsman());
			loginParam.setImei(miguUser.getImei());
			loginParam.setImsi(miguUser.getImsi());
			loginParam.setMobile(miguUser.getUserName());
			loginParam.setPassword(miguUser.getPassword());
			loginParam.setReleaseVersion(miguUser.getRelease());
			String wifiInfo = miguUser.getWifiInfo();
			if (StringUtils.isNotBlank(wifiInfo)) {
				int index = wifiInfo.indexOf("|");
				if (index > 0) {
					loginParam.setWifiMac(wifiInfo.substring(0, index));
				}
			}
			result = MiguAuthorization.doLogin(loginParam);
			if (result != null) {
				String status = result.get("status");
				if (StringUtils.isNotBlank(status) && "1".equals(status)) {
					code = 1;
				}
			}
		} catch (Exception e) {
			LOGGER.error("校验咪咕账号出错 {} ", JSONObject.toJSONString(loginParam), e);
		}
		if (result == null) {
			LOGGER.warn("咪咕账号校验 {} {}", new Object[] { miguUser.getUserName(), null });
		} else {
			LOGGER.warn("咪咕账号校验 {} {}", new Object[] { miguUser.getUserName(), JSONObject.toJSONString(result) });
		}
		return code;

	}

	/**
	 * 
	 * checkMiguUser:咪咕账号校验
	 * 
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @param miguUser
	 * @return
	 */
	private int checkMiguUser(MiguUser miguUser) {
		int code = -1;
		Response result = null;
		Request request = new Request();
		try {
			request.setTimeout(20000);
			Map<String, String> params = new HashMap<String, String>();
			params.put("hsman", miguUser.getHsman());
			params.put("hstype", miguUser.getHsman());
			params.put("buildVersion", miguUser.getBuildVersion());
			params.put("releaseVersion", miguUser.getRelease());
			params.put("buildId", miguUser.getBuildId());
			params.put("imei", miguUser.getImei());
			params.put("imsi", miguUser.getImsi());
			params.put("mobile", miguUser.getUserName());
			params.put("password", miguUser.getPassword());
			params.put("androidId", miguUser.getAndroidId());
			String wifiInfo = miguUser.getWifiInfo();
			if (StringUtils.isNotBlank(wifiInfo)) {
				int index = wifiInfo.indexOf("|");
				if (index > 0) {
					params.put("wifiMac", wifiInfo.substring(0, index));
				}
			}
			request.setParams(params);
			request.setUrl(MIGU_CHECK_URL);
			result = HttpClientUtil.doPost(request);
			if (result != null) {
				String data = result.getData();
				if (StringUtils.isNotBlank(data)) {
					JSONObject resultObj = JSONObject.parseObject(data);
					if (resultObj != null) {
						code = resultObj.getIntValue("resultCode");
					}
				}
			} else {
				code = -2;
			}
		} catch (Exception e) {
			code = -3;
			LOGGER.error("校验咪咕账号出错 {} ", JSONObject.toJSONString(request.getParams()), e);
		}
		if (result == null) {
			LOGGER.warn("咪咕账号校验 {} {}", new Object[] { miguUser.getUserName(), null });
		} else {
			LOGGER.warn("咪咕账号校验 {} {}", new Object[] { miguUser.getUserName(), result.getData() });
		}
		return code;
	}

	public MiguUser getMiguUser() {
		return miguUser;
	}

	public void setMiguUser(MiguUser miguUser) {
		this.miguUser = miguUser;
	}

}
